import React from 'react';
import { Modal, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import styles from '../index.less';
import $ from 'jquery';
import webuploader from 'webuploader';

interface UploadModelProps {
  modalVisible: boolean;
  onSubmit: (callback: string) => void;
  onCancel: () => void;
}

class Upload extends React.Component {
  constructor(props: any) {
    super(props);
  }

  componentDidMount() {
    let prop = this.props.parent;

    let state = 'pending';

    const chunkSize = 2 * 1024 * 1024;
    
    const uploader = webuploader.create({
      // swf文件路径
      swf: '../../../../node_modules/webuploader/dist/Uploader.swf',

      // 文件接收服务端。
      server: '/api/web-uploader/upload',

      // 选择文件的按钮。可选。
      // 内部根据当前运行是创建，可能是input元素，也可能是flash.
      pick: '#picker',
      label: '点击选择文件',
      // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
      resize: false,
      compress:false,//图片不压缩
      headers: {
        Authorization: localStorage.getItem('token'),
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      //过滤
      accept: {
        title: 'Files',
        // extensions: 'jpg,jpeg,png,bmp,mkv,mp4,avi,mov,ogv,wmv',
        extensions: 'jpg,jpeg,png,bmp,mp4',
        mimeTypes: 'image/jpeg,image/png,image/bmp,video/mp4',
      },
      chunked: true,
      chunkSize: chunkSize, // 字节 1M分块
      threads: 5,
      //禁用拖追
      disableGlobalDnd: true,
      // fileNumLimit: 1,
      fileSizeLimit: 1024 * 1024 * 1024 * 1024, // 1024 M
      fileSingleSizeLimit: 1024 * 1024 * 1024 * 1024, // 1024 M
      formData: {
        md5: '',
        // guid: webuploader.Base.guid(),
        chunkSize: chunkSize,
      },
    });

    uploader.on("uploadStart", function (file:string) {
      console.log("uploadStart");
      const guid = webuploader.Base.guid()
      uploader.options.formData.guid = guid;
      // console.log(guid);
    });
    // 当有文件被添加进队列的时候
    uploader.on('fileQueued', function (file: string) {
      console.log("fileQueued")
      $('#uploadList').find('.error').remove();
      $('#uploadList').append(
        '<div id="' +
          file.id +
          '" class="item">' +
          '<h4 class="info">' +
          file.name +
          '</h4>' +
          '<p class="state">等待上传...</p>' +
          '</div>',
      );
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function (file: string, percentage: number) {
      console.log(percentage)
      if(percentage == 1){
        percentage = 0.995;
      }
      var $li = $('#' + file.id),
        $percent = $li.find('.progress .progress-bar');

      // 避免重复创建
      if (!$percent.length) {
        $percent = $(
          '<div class="progress progress-striped active">' +
            '<span class="text">' +
            // Math.round(percentage) +
            Math.floor(percentage * 100) +
            '</span>' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>',
        )
          .appendTo($li)
          .find('.progress-bar');
      }

      $li.find('p.state').text('上传中').removeClass('success');
      // $li.find('.text').html(Math.round(percentage * 100) + '%');
      $li.find('.text').html(Math.floor(percentage * 100) + '%');
      $percent.css('width', percentage * 100 + '%');
    });

    uploader.on('uploadSuccess', function (file: string, response) {
      console.log("uploadSuccess")
      // return;
      if(response.code === 200){
        $('#' + file.id)
        .find('p.state')
        .text('已上传')
        .addClass('success');
        $('#' + file.id).find(".text").html("100%")
        $('#' + file.id).find(".progress-bar").css('width','100%');
        prop.onSubmit('success');
        
      }else{
        $('#' + file.id)
        .find('p.state')
        .text('上传出错，' + response.message)
        .addClass('error');
      }
      
    });

    uploader.on('uploadError', function (file: string) {
      $('#' + file.id)
        .find('p.state')
        .text('上传出错')
        .addClass('error');
    });

    uploader.on('uploadComplete', function (file: string) {
      console.log("uploadComplete")
      setTimeout(() => {
        $('#' + file.id)
        .find('.progress')
        .fadeOut();
      }, 0);
     
    });

    $('#upload').on('click', function () {
      if ($('#uploadList').html() == '') {
        $('#uploadList').append("<p class='error'>请选择上传文件</p>");
      } else {
        if (state === 'uploading') {
          uploader.stop();
        } else {
          uploader.upload();
        }
      }
    });
  }
  render() {
    return (
      <div className={styles.uploadContainer}>
        <span className="des">提示：支持格式为：jpg,jpeg,png,bmp,mp4</span>
        <div id="uploader" className="wu-example">
          {/* <!--用来存放文件信息--> */}
          <div id="uploadList" className="uploader-list"></div>
          <div className="btns">
            <div id="picker">
              <UploadOutlined />
              <span style={{ marginLeft: 8 }}>选择文件</span>
            </div>
            <Button id="upload" type="primary">
              开始上传
            </Button>
          </div>
        </div>
      </div>
    );
  }
}
const UploadModel: React.FC<UploadModelProps> = (props) => {
  const { modalVisible, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      maskClosable={false}
      title="上传素材"
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <Upload parent={props} />
    </Modal>
  );
};

export default UploadModel;
